package com.just.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;


public class FileDownServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1获取下载文件路径
        //变成流获取他的绝对路径，相对路径
        //String realPath = this.getServletContext().getRealPath("/1.jpg");
        String realPath = "D:\\software\\javaproject\\fileLoad\\target\\classes\\2.jpg";
        System.out.println("下载文件的路径:" + realPath);

//        2下载文件名是什么
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);

//        3设置想办法让浏览器支持下载我们需要的东西
        resp.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
//        4获取下载文件的输入流
        FileInputStream in = new FileInputStream(realPath);
//        5创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
//        6获取OutPutStream对象
        ServletOutputStream out = resp.getOutputStream();
//        7将FileInPutStream流写到缓冲区buffer,使用outputstream将缓冲区中的数据输出到客户端
        while((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
